package com.mpj.fiter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.util.Locale;

/**
 * Created by Administrator on 2016/6/24 0024.
 */
public class LanguageFiter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        setLocale(servletRequest, servletResponse, filterChain);
    }

    @Override
    public void destroy() {

    }

    private void setLocale(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object temp = request.getSession().getAttribute("language");
        if (temp != null) {
            String language = temp.toString();
            String[] localeCode = language.split("_");
            System.out.println(request.getLocale());
            System.out.println(response.getLocale());
            Locale locale = new Locale(localeCode[0], localeCode[1]);
            response.setLocale(locale);
            System.out.println(response.getLocale());

        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
